package com.learn.demo.netty.chat;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;


/**
 * 聊天客户端
 */
public class ChatDemoClient {

    private int port;
    private String host;

    public ChatDemoClient(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void run() throws InterruptedException {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(eventLoopGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            //向pipeline中加入解码器
                            pipeline.addLast("decoder", new StringDecoder());
                            //向pipeline中加入编码器
                            pipeline.addLast("encoder", new StringEncoder());
                            //加入自己的处理handler
                            pipeline.addLast(new ChatDemoClientHandler());
                        }
                    });
            ChannelFuture channelFuture = bootstrap.connect(host, port).sync();
            //获得channel
            Channel channel = channelFuture.channel();
            System.out.println("===============" + channel.localAddress() + "===============");
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                String nextLine = scanner.nextLine();
                if(nextLine.equals("quit")){
                    break;
                }
                channel.writeAndFlush(nextLine + "\r\n");
            }

        } finally {
            eventLoopGroup.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new ChatDemoClient(7000, "127.0.0.1").run();
    }
}
